package com.allenblog.job;

import com.allenblog.domain.entity.Article;
import com.allenblog.service.ArticleService;
import com.allenblog.utils.RedisCache;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务每隔10分钟把Redis中的浏览量更新到数据库中
 */
@Component
public class UpdateViewCountJob {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private RedisCache redisCache;

    @Scheduled(cron = "0/5 * * * * ?")
    public void updateViewCount() {

        //获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");

        List<Article> articles = viewCountMap.entrySet()
                .stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()),
                        entry.getValue().longValue())).collect(Collectors.toList());
        //更新到数据库中
//        articleService.updateBatchById(articles);
        articles.forEach(
                e -> {
                    UpdateWrapper<Article> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", e.getId());
                    updateWrapper.set("view_count", e.getViewCount());
                    articleService.update(updateWrapper);
                }
        );
    }
}

